package labox.innovation.gameserver.network.clientpackets;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import labox.innovation.config.Config;
import labox.innovation.gameserver.LoginServerThread; //import labox.innovation.gameserver.LoginServerThread.SessionKey;
import labox.innovation.gameserver.network.L2GameClient;
import labox.innovation.util.Util;

/**
 * 客户端发上来等待游戏服务器认证的消息
 * 
 * @version $Revision: 1.9.2.3.2.4 $ $Date: 2005/03/27 15:29:30 $
 */
public final class AuthLogin extends L2GameClientPacket {

	private static final String _C__08_AUTHLOGIN = "[C] 08 AuthLogin";

	private static final Logger _log = LoggerFactory.getLogger(AuthLogin.class.getName());

	// loginName + keys must match what the loginserver used.
	private String _loginName;

	private int _sessionId;

	//检查提交的账户名称是否符合标准的正则表达式
	private static final Pattern NAME_PATTERN = Pattern.compile(Config.ACCOUNT_NAME_TEMPLATE);

	/**
	 * @param decrypt
	 */
	@Override
	protected void readImpl() {
		_sessionId = readInt();
		_loginName = readString();
	}

	@Override
	protected void runImpl() {
		if (_log.isDebugEnabled()) {
			_log.debug("user:" + _loginName, _loginName);
			_log.debug("key:" + _sessionId, _sessionId);
		}

		//做简单的基础验证
		if (_loginName == null || _loginName.length() == 0 || !isValidName(_loginName)) {
			_log.warn("Read invalid account name is:" + _loginName, Config.SERVER_ID, null);
			return;
		}

		L2GameClient client = getClient();

		// 向登陆服务器查询key的正确性,避免潜在的攻击
		if (client.getAccountName() == null) {
			client.setAccountName(_loginName);
			//记录当前账户已经进入了游戏服务器但还没有进入游戏世界
			LoginServerThread.getInstance().addGameServerLogin(_loginName, client);
			//向登陆服务器验证此账户是否已经授权
			LoginServerThread.getInstance().addWaitingClientAndSendRequest(_loginName, client, _sessionId);
		}
	}

	/* (non-Javadoc)
	 * @see labox.innovation.gameserver.clientpackets.ClientBasePacket#getType()
	 */
	@Override
	public String getType() {
		return _C__08_AUTHLOGIN;
	}

	public boolean isValidName(String text) {
		if (!Util.isAlphaNumeric(text))
			return false;

		Matcher regexp = NAME_PATTERN.matcher(text);
		if (!regexp.matches()) {
			return false;
		}
		return true;
	}
}
